package org.luxor.commons.security.component;

import org.luxor.commons.security.config.WebSecurityProperties;
import org.luxor.commons.security.constant.SecurityConstants;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.provider.authentication.BearerTokenExtractor;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

import javax.servlet.http.HttpServletRequest;

/**
 * 改造 {@link BearerTokenExtractor} 对公开权限的请求不进行校验
 *
 * @author caiqy
 * @date 2020.05.15
 */
public class RestBearerTokenExtractor extends BearerTokenExtractor {
    private final PathMatcher pathMatcher = new AntPathMatcher();
    private final String[] DEFAULT_LOGIN_URIS = new String[]{"/login", "/logout", "/me"};

    private final WebSecurityProperties properties;

    public RestBearerTokenExtractor(WebSecurityProperties properties) {
        this.properties = properties;
    }

    @Override
    public Authentication extract(HttpServletRequest request) {
        // 默认登陆接口白名单配置
        for (String uri : DEFAULT_LOGIN_URIS) {
            if (pathMatcher.match(uri, request.getRequestURI())) {
                return null;
            }
        }
        // 收集默认白名单配置
        for (String uri : SecurityConstants.DEFAULT_ANON_URIS) {
            if (pathMatcher.match(uri, request.getRequestURI())) {
                return null;
            }
        }
        // 收集白名单配置
        String[] anonUrls = properties.getAnonUris();
        for (String uri : anonUrls) {
            if (pathMatcher.match(uri, request.getRequestURI())) {
                return null;
            }
        }
        return super.extract(request);
    }


}
